package com.txby.datasources;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

/**
 * 配置多数据源
 */
@Configuration
public class DynamicDataSourceConfig {
	/*@Autowired
    StringEncryptor stringEncryptor;*/
    @Bean
    @ConfigurationProperties("spring.datasource.druid.first")
    public DruidDataSource firstDataSource(){
    	 return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.second")
    public DruidDataSource secondDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DynamicDataSource dataSource(DruidDataSource firstDataSource, DruidDataSource secondDataSource) {
    	/*firstDataSource.setUrl(EncryptUtils.decryptByENC(firstDataSource.getUrl()));  
    	firstDataSource.setPassword(EncryptUtils.decryptByENC(firstDataSource.getPassword()));  
    	secondDataSource.setUrl(EncryptUtils.decryptByENC(firstDataSource.getUrl()));  
    	secondDataSource.setPassword(EncryptUtils.decryptByENC(firstDataSource.getPassword()));  */
        Map<String, DataSource> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceNames.FIRST, firstDataSource);
        targetDataSources.put(DataSourceNames.SECOND, secondDataSource);
        return new DynamicDataSource(firstDataSource, targetDataSources);
    }
}
